package com.itheima.youdianda.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.youdianda.common.R;
import com.itheima.youdianda.entity.YddUser;
import com.itheima.youdianda.service.YddUserService;
import com.itheima.youdianda.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/home/index")
public class YddUserLoginController {

    @Autowired
    private YddUserService yddUserService;

    /**
     * 前端-登录
     *
     * @param yddUser
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody YddUser yddUser) {
        //获取登录用户输入的手机号以及密码
        String mobile = yddUser.getMobile();

        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile,mobile);
        YddUser one = yddUserService.getOne(wrapper);

        if (one == null) {
            return R.error("账号不存在");
        }

        String yddUserPassword = yddUser.getPassword();
        String s = generatePassword(yddUserPassword);
        //一下为暂时注释内容

        if (one.getPassword().equals(s)) {
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();


            tokenMap.put("userId", one.getId());

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);

            return R.success("token", JwtUtils.getToken(tokenMap));
        }
        return R.error("密码错误");
    }
    /** md5加密
     * @param password 密码
     */
    private String generatePassword(String password){
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

}
    


